import { spawn } from "node:child_process";
import path from "node:path";
import fs from "node:fs";

const tagStr = "--- ";
function exec(cmd: string, cwd: string) {
  let hasReporter = false;
  return new Promise((resolve, reject) => {
    let errStr: string = "";
    // 放慢速度
    const cp = spawn("cmd", ["/c", cmd], {
      stdio: "pipe",
      timeout: 1000 * 60 * 20,
      cwd,
    });

    cp.stdout.on("data", (val) => {
      const data = val.toString();
      console.log(data);
      if (/Build\s+Init/.test(data)) {
        hasReporter = true;
        console.log("---has reporter---");
      }
    });
    cp.stderr.on("data", (err) => {
      console.log("runtime error:", err.toString());
    });
    cp.on("error", (err) => {
      console.log("process error:", err.toString());
    });

    cp.on("exit", (code, signal) => {
      if (code) {
        reject(`${errStr}\nExit code:${code} signal: ${signal}`);
      } else {
        resolve(hasReporter);
      }
    });
  });
}

async function execPath(dir: string) {
  if (!fs.existsSync(dir)) {
    console.log(dir + " not exist.");
    return;
  }
  const data = fs.readdirSync(dir);
  console.log(`'---Start running cmd, Total:${data.length}`);
  let suc = 0;
  let fail = 0;
  let reporter = 0;
  const noReporterArr: string[] = [];
  const failNameArr: string[] = [];
  for (let fileName of data) {
    const prjDir = path.resolve(dir, fileName);
    if (fs.statSync(prjDir).isDirectory()) {
      try {
        const rslt = await exec("pnpm build", prjDir);
        console.log(`---${path.basename(prjDir)} done---`);
        suc += 1;
        if (rslt) {
          reporter += 1;
        } else {
          noReporterArr.push(fileName);
        }
      } catch (e) {
        console.error(`---${path.basename(prjDir)} error---`, e.message);
        fail += 1;
        failNameArr.push(fileName);
      }
    }
  }
  console.log(
    `'---All cmd is finished, suc: ${suc} , fail: ${fail} Total:${data.length} ,reporter ${reporter}`
  );
  if (failNameArr.length) {
    console.log(`---Fail :${failNameArr.join(",")}---`);
  }

  if (noReporterArr.length) {
    console.log(`---No Reporter :${noReporterArr.join(",")}---`);
  }
}

execPath(path.resolve(__dirname, "../projects"));
